<template>
  <div>
    <a-skeleton :loading="loadingEditor" avatar :paragraph="{ rows: 2 }" active> </a-skeleton>
    <Editor
      v-model="innerContent"
      :api-key="tinyMCEApiKey"
      :init="editorInit"
      @init="onEditorInit"
      @blur="handleBlurFn"
    />
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, watch, nextTick } from "vue";
import Editor from "@tinymce/tinymce-vue";
import { getTinyMCELangInfo } from "/@/utils/tinymce";
// import { uploadFile, UploadFileResult } from "/@/api/common";
import env from "/@/base/env";

export default defineComponent({
  components: {
    Editor,
  },
  props: {
    value: String,
    label: { default: "文章内容", type: String },
  },
  setup(props, ctx) {
    const tinyMCEApiKey = env.tinymceKey;
    const innerContent = ref("");

    const editorInit = {
      height: 440,
      menubar: true,
      // plugins: "image,lists,advlist,fullscreen,code,preview,print",
      plugins: "link",
      contextmenu: "bold copy link paste",
      toolbar1:
        "undo redo | link bold italic underline strikethrough | fontselect fontsizeselect formatselect | alignleft aligncenter alignright alignjustify",
      toolbar2: "forecolor backcolor removeformat | preview  | code",
      // images_upload_handler: async function (blobInfo, success, failure) {
      //   const file = blobInfo.blob(); //转化为易于理解的file对象
      //   const re = (await uploadFile({
      //     file,
      //   })) as UploadFileResult;
      //   if (re) {
      //     success(re.url);
      //   } else {
      //     console.log("upload fail", re);
      //     failure("上传失败，请稍候再试");
      //   }
      // },
    };
    console.info("innerContent==>", innerContent.value);
    const langInfo = getTinyMCELangInfo();
    if (langInfo) {
      Object.assign(editorInit, langInfo);
    }
    const loadingEditor = ref(true);
    watch(
      () => props.value,
      (v) => {
        nextTick(() => {
          innerContent.value = v || "";
        });
      }
    );
    watch(loadingEditor, (v) => {
      if (v) {
        nextTick(() => {
          innerContent.value = props.value || "";
        });
      }
    });
    watch(innerContent, (v) => {
      ctx.emit("change", v);
    });
    function onEditorInit() {
      loadingEditor.value = false;
      nextTick(() => {
        innerContent.value = props.value || "";
      });
    }
    function handleBlurFn(v) {
      ctx.emit("change", innerContent.value);
    }
    return {
      loadingEditor,
      tinyMCEApiKey,
      editorInit,
      onEditorInit,
      innerContent,
      handleBlurFn,
    };
  },
});
</script>
<style lang="less" scoped>
:deep(textarea) {
  display: none;
}
</style>
